package main.com.hjy.jdbc.utils;



import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBPoolUtils {
        //创建数据库的数据源对象
        private static DataSource dataSource = null;

        //将连接存储在多线程中,让一个链接一个线程
        private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

        static
        {
            try {
                Properties props = new Properties();
                props.load(DBPoolUtils.class.getClassLoader().getResourceAsStream("db.properties"));
                dataSource = DruidDataSourceFactory.createDataSource(props);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public static  Connection  getConnection()
        {
            //到多线程中获取一个数据库连接
            Connection con = threadLocal.get();
            //判断获取到的数据库连接是否为null
            try {
                if(con == null)
                {
                    //如果获取到的数据库连接为null,则从数据源中获取到一个链接
                    con = dataSource.getConnection();
                    //将获取到的连接再存储到多线程中
                    threadLocal.set(con);
                    //获取到连接以后,返回给使用连接的地方
                    return con;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return con;
        }


    }





